package com.hontech.bv.net.device

import android.os.Handler
import com.hontech.bv.net.cfg.Cfg
import com.hontech.bv.task.PromiseTask
import com.hontech.bv.task.TaskThread
import com.hontech.bv.utils.log
import java.io.IOException

object TcpConnTask : Handler( TaskThread("tcp conn task").looper )

object TcpMod : Runnable {

    private var client: Client? = null

    fun init() {
        TcpConnTask.post(this)
    }

    suspend fun request(frame: Frame, timeout: Long): Frame {

        return PromiseTask {
            if (client == null) {
                throw IOException("tcp 没有连接")
            }
            client!!.request(frame, timeout)
        }.exec(TcpConnTask).await()
    }

    suspend inline fun <reified T, reified R> request(
        req: Int,
        v: T,
        timeout: Long = 10 * 1000L
    ): R {
        val res = request(Frame.fromJson(req, v), timeout)
        if (res.req != req) {
            throw IllegalStateException("req invalid")
        }
        return res.parse()
    }

    fun reconnect() {
        client = null
        TcpConnTask.postDelayed(this, 10 * 1000L)
    }

    override fun run() {

        if ((client != null) && client!!.connectFlag) {
            log("已经连接")
            return
        }

        try {
            client = Client(Cfg.REMOTE_ADDR, Cfg.TCP_PORT)

        } catch (e: Exception) {
            e.printStackTrace()
            reconnect()
        }
    }
}